<template>
  <div class="food-search-page">
    <!-- 搜索区域 -->
    <el-card class="search-section">
      <div class="search-header">
        <div class="search-input">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索食物..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <el-button type="primary" @click="showAddDialog">
          添加食物
        </el-button>
      </div>
      
      <!-- 分类标签 -->
      <div class="category-tags" v-if="categories.length">
        <el-tag
          v-for="category in categories"
          :key="category"
          :class="{ active: currentCategory === category }"
          @click="handleCategoryClick(category)"
          class="category-tag"
        >
          {{ category }}
        </el-tag>
      </div>
    </el-card>

    <!-- 食物列表 -->
    <div class="food-list" v-loading="loading">
      <el-empty v-if="!foods.length" description="暂无相关食物" />
      
      <el-row :gutter="20">
        <el-col 
          v-for="food in foods" 
          :key="food.foodId"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="food-card" shadow="hover">
            <el-image
              :src="food.imageUrl"
              fit="cover"
              class="food-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            
            <div class="food-info">
              <div class="food-header">
                <h3 class="food-name">{{ food.name }}</h3>
                <el-dropdown trigger="click" @command="handleCommand">
                  <el-button :text="true">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{ type: 'delete', food }">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="food-details">
                <div class="detail-item">
                  <span class="label">热量：</span>
                  <span class="value">{{ food.calories }}千卡</span>
                </div>
                <div class="detail-item">
                  <span class="label">蛋白质：</span>
                  <span class="value">{{ food.protein }}g</span>
                </div>
                <div class="detail-item">
                  <span class="label">碳水：</span>
                  <span class="value">{{ food.carbohydrates }}g</span>
                </div>
                <div class="detail-item">
                  <span class="label">脂肪：</span>
                  <span class="value">{{ food.fat }}g</span>
                </div>
              </div>
              <div class="food-actions">
                <el-button
                  type="success"
                  text
                  @click="showUploadDialog(food)"
                >
                  上传图片
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 添加图片上传弹窗 -->
    <el-dialog
      title="上传食物图片"
      v-model="uploadDialogVisible"
      width="400px"
      :before-close="handleUploadDialogClose"
    >
      <div class="preview-container" v-if="previewUrl">
        <img :src="previewUrl" class="preview-image" />
      </div>
      <el-upload
        class="food-image-uploader"
        action="#"
        :show-file-list="true"
        :on-change="handleFileChange"
        :auto-upload="false"
        :limit="1"
        ref="uploadRef"
      >
        <el-button type="primary">选择图片</el-button>
        <template #tip>
          <div class="el-upload__tip">只能上传 jpg/png 文件，且不超过 2MB</div>
        </template>
      </el-upload>
      <template #footer>
        <el-button 
          @click="handleUploadDialogClose"
          :disabled="uploading"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="uploading"
          :disabled="!tempImageFile || uploading"
          @click="handleUploadImage"
        >
          上传
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加食物弹窗 -->
    <el-dialog
      title="添加食物"
      v-model="addDialogVisible"
      width="500px"
    >
      <el-form
        ref="addFormRef"
        :model="foodForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="foodForm.name" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="foodForm.category" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="foodForm.unit" />
        </el-form-item>
        <el-form-item label="热量" prop="calories">
          <el-input-number 
            v-model="foodForm.calories" 
            :min="0" 
            :max="9999"
            :precision="1"
          />
          <span class="unit">千卡</span>
        </el-form-item>
        <el-form-item label="蛋白质" prop="protein">
          <el-input-number 
            v-model="foodForm.protein" 
            :min="0" 
            :max="100"
            :precision="1" 
            :step="0.1" 
          />
          <span class="unit">g</span>
        </el-form-item>
        <el-form-item label="碳水" prop="carbohydrates">
          <el-input-number 
            v-model="foodForm.carbohydrates" 
            :min="0" 
            :max="100"
            :precision="1" 
            :step="0.1" 
          />
          <span class="unit">g</span>
        </el-form-item>
        <el-form-item label="脂肪" prop="fat">
          <el-input-number 
            v-model="foodForm.fat" 
            :min="0" 
            :max="100"
            :precision="1" 
            :step="0.1" 
          />
          <span class="unit">g</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleAddFood">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Picture, More, Delete } from '@element-plus/icons-vue'
import { searchFoods, getAllCategories, getFoodsByCategory, uploadFoodImage, addFood, deleteFood } from '@/api/food'

const loading = ref(false)
const searchKeyword = ref('')
const foods = ref([])
const categories = ref([])
const currentCategory = ref('')
const uploadDialogVisible = ref(false)
const currentFood = ref(null)
const uploadRef = ref(null)
const uploading = ref(false)
const previewUrl = ref('')
const tempImageFile = ref(null)
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const submitting = ref(false)
const foodForm = ref({
  name: '',
  category: '',
  unit: '克',
  calories: 0,
  protein: 0,
  carbohydrates: 0,
  fat: 0
})
const rules = {
  name: [
    { required: true, message: '请输入食物名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入食物分类', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入计量单位', trigger: 'blur' }
  ],
  calories: [
    { required: true, message: '请输入热量', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '热量必须在 0-9999 之间', trigger: 'blur' }
  ],
  protein: [
    { required: true, message: '请输入蛋白质含量', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '蛋白质含量必须在 0-100 之间', trigger: 'blur' }
  ],
  carbohydrates: [
    { required: true, message: '请输入碳水化合物含量', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '碳水化合物含量必须在 0-100 之间', trigger: 'blur' }
  ],
  fat: [
    { required: true, message: '请输入脂肪含量', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '脂肪含量必须在 0-100 之间', trigger: 'blur' }
  ]
}

let searchTimer = null

// 获取所有分类
const fetchCategories = async () => {
  try {
    const response = await getAllCategories()
    if (response?.success) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 处理搜索
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  searchTimer = setTimeout(async () => {
    loading.value = true
    try {
      const response = await searchFoods(searchKeyword.value)
      if (response?.success) {
        foods.value = response.data || []
        currentCategory.value = ''
      }
    } catch (error) {
      console.error('搜索失败:', error)
      ElMessage.error('搜索失败')
    } finally {
      loading.value = false
    }
  }, 300)
}

// 处理分类点击
const handleCategoryClick = async (category) => {
  if (currentCategory.value === category) {
    currentCategory.value = ''
    return
  }
  
  currentCategory.value = category
  loading.value = true
  
  try {
    const response = await getFoodsByCategory(category)
    if (response?.success) {
      foods.value = response.data || []
      searchKeyword.value = ''
    }
  } catch (error) {
    console.error('获取分类食物失败:', error)
    ElMessage.error('获取分类食物失败')
  } finally {
    loading.value = false
  }
}

// 处理文件变化
const handleFileChange = (uploadFile) => {
  const file = uploadFile.raw
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  tempImageFile.value = file
  previewUrl.value = URL.createObjectURL(file)

  return false
}

// 处理图片上传
const handleUploadImage = async () => {
  if (!tempImageFile.value || !currentFood.value?.foodId) {
    ElMessage.warning('请先选择图片')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', tempImageFile.value)
    
    const response = await uploadFoodImage(currentFood.value.foodId, formData)
    
    if (response?.success) {
      ElMessage.success('图片上传成功')
      if (currentCategory.value) {
        await handleCategoryClick(currentCategory.value)
      } else if (searchKeyword.value) {
        await handleSearch()
      } else {
        const foodResponse = await getFoodsByCategory(currentFood.value.category)
        if (foodResponse?.success) {
          foods.value = foodResponse.data || []
        }
      }
      uploadDialogVisible.value = false
    } else {
      throw new Error(response?.message || '上传失败')
    }
  } catch (error) {
    console.error('��传图片失败，详细错误:', error)
    console.error('错误响应:', error.response)
    ElMessage.error(error.message || '上传图片失败')
  } finally {
    uploading.value = false
    if (previewUrl.value && previewUrl.value.startsWith('blob:')) {
      URL.revokeObjectURL(previewUrl.value)
    }
    previewUrl.value = ''
    tempImageFile.value = null
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
  }
}

// 处理上传弹窗关闭
const handleUploadDialogClose = () => {
  if (uploading.value) {
    ElMessage.warning('正在上传中，请稍候...')
    return
  }
  uploadDialogVisible.value = false
  if (previewUrl.value && previewUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(previewUrl.value)
  }
  previewUrl.value = ''
  tempImageFile.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 显示上传图片弹窗
const showUploadDialog = (food) => {
  currentFood.value = food
  previewUrl.value = food.imageUrl || ''
  tempImageFile.value = null
  uploadDialogVisible.value = true
}

// 显示添加食物弹窗
const showAddDialog = () => {
  foodForm.value = {
    name: '',
    category: '',
    unit: '克',
    calories: 0,
    protein: 0,
    carbohydrates: 0,
    fat: 0
  }
  addDialogVisible.value = true
}

// 处理添加���物
const handleAddFood = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    submitting.value = true
    
    const response = await addFood(foodForm.value)
    
    if (response?.success) {
      ElMessage.success('添加成功')
      addDialogVisible.value = false
      await fetchCategories()
      if (currentCategory.value) {
        await handleCategoryClick(currentCategory.value)
      } else if (searchKeyword.value) {
        await handleSearch()
      } else {
        const foodResponse = await getFoodsByCategory(foodForm.value.category)
        if (foodResponse?.success) {
          foods.value = foodResponse.data || []
          if (!currentCategory.value) {
            currentCategory.value = foodForm.value.category
          }
        }
      }
    } else {
      throw new Error(response?.message || '添加失败')
    }
  } catch (error) {
    console.error('添加食物失败:', error)
    ElMessage.error(error.message || '添加失败')
  } finally {
    submitting.value = false
  }
}

// 处理下拉菜单命令
const handleCommand = async ({ type, food }) => {
  if (type === 'delete') {
    try {
      await ElMessageBox.confirm(
        '确定要删除这个食物吗？此操作不可恢复。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      const response = await deleteFood(food.foodId)
      if (response?.success) {
        ElMessage.success('删除成功')
        // 从列表中移除该食物
        foods.value = foods.value.filter(item => item.foodId !== food.foodId)
      } else {
        throw new Error(response?.message || '删除失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除食物失败:', error)
        ElMessage.error(error.message || '删除失败')
      }
    }
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<style lang="scss" scoped>
.food-search-page {
  padding: 20px;
  
  .search-section {
    margin-bottom: 20px;
    
    .search-header {
      display: flex;
      gap: 16px;
      margin-bottom: 16px;
      
      .search-input {
        flex: 1;
      }
    }
    
    .category-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .category-tag {
        cursor: pointer;
        
        &.active {
          font-weight: bold;
        }
      }
    }
  }
  
  .food-list {
    .food-card {
      margin-bottom: 20px;
      
      .food-image {
        width: 100%;
        height: 200px;
        border-radius: 4px;
        overflow: hidden;
        
        .image-placeholder {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background-color: #f5f7fa;
          color: #909399;
          font-size: 24px;
        }
      }
      
      .food-info {
        padding: 12px 0;
        
        .food-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 12px;
          
          .food-name {
            margin: 0;
            font-size: 16px;
            flex: 1;
          }
        }
        
        .food-details {
          .detail-item {
            margin-bottom: 4px;
            
            .label {
              color: var(--el-text-color-secondary);
            }
            
            .value {
              margin-left: 4px;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
  
  .food-image-upload {
    .upload-placeholder {
      width: 200px;
      height: 200px;
      border: 1px dashed var(--el-border-color);
      border-radius: 4px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      
      &:hover {
        border-color: var(--el-color-primary);
      }
      
      .el-icon {
        font-size: 24px;
        color: var(--el-text-color-secondary);
        margin-bottom: 8px;
      }
      
      .text {
        color: var(--el-text-color-secondary);
      }
    }
    
    .upload-image {
      width: 200px;
      height: 200px;
      object-fit: cover;
      border-radius: 4px;
    }
  }
  
  .unit {
    margin-left: 8px;
    color: var(--el-text-color-secondary);
  }

  .preview-container {
    text-align: center;
    margin-bottom: 20px;
    
    .preview-image {
      max-width: 100%;
      max-height: 300px;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }
}

@media (max-width: 768px) {
  .food-search-page {
    padding: 10px;
    
    .search-header {
      flex-direction: column;
    }
  }
}
</style> 